<style type="text/css">
.ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
</style>
<div class="container-fluid">
	<div class="row-fluid">			
		<div class="span12">
		
			<div class="widget-box">
        <div class="widget-title"> <span class="icon"> <i class="icon-edit"></i></span>
          <h5><?php echo $title?></h5>
          <span class="label label-info" style="cursor:pointer" onclick="window.location.reload();"><i class="icon-refresh"></i>&nbsp;刷新</span>
        </div>
        <div class="widget-content nopadding">
          <form action="#" method="post" class="form-horizontal" id="myform" name="myform" autocomplete='off'>
            <div class="control-group">
              <label class="control-label">角色权限</label>
              <div class="controls">
                <ul id="rightsTree" class="ztree span4"></ul>
              </div>
            </div>
                 <div class="control-group">
              <label class="control-label">权限内容</label>
              <div class="controls" id="menu_con">
			             
              </div>
            </div>
                 <div class="form-actions">
                      <button type="button" class="btn btn-success"  onclick='addNode()'>新增节点</button>
                      <button type="button" class="btn btn-success"  onclick='sub()'>保&nbsp;&nbsp;存</button>
                </div>
          </form>
        </div>
      </div>			
		</div>
	</div>
</div>
<script  type="text/javascript">
var model=[];
var menu=[];
var act=[];
  var setting = {
      check: {enable: false},
      edit: {
		enable: true,
		editNameSelectAll: true,
		showRemoveBtn: showRemoveBtn,
		showRenameBtn: false,
		
	  }, view: {
			fontCss: setFontCss
	  },
      callback: {  
          beforeClick: beforeClick,  
          onClick: onClick  ,
      	  beforeRemove: zTreeBeforeRemove
      },
      data: {
        simpleData: {enable: true}
      }
    };
    var zNodes = [<?php echo $accessStr?>];
    var treeObj =$.fn.zTree.init($("#rightsTree"), setting, zNodes);
    function beforeClick(treeId,treeNode,clickFlag){
    	return true;
    }
    function showRemoveBtn(treeId,treeNode){
    	return treeNode.isNew;
    }
    var newCount = 1;
    function onClick(event,treeId,treeNode,clickFlag){
    	if(treeNode.id==0){
    		 myAlert("该节点不允许编辑!");
    		 return;
    	}
    	$('#menu_con').find('table').hide();
    	if($('#table'+treeNode.id).length>0){
    		$('#table'+treeNode.id).show();
    	}else{
    		var table=createTable(treeNode);
    		$('#menu_con').append(table);
    	}
    }
    function zTreeBeforeRemove(treeId, treeNode){
    	  if(!treeNode.isNew){
    		  myAlert("已启用的菜单不允许删除!");
    		  return false;
    	  } 
    	  return true;
    }
    function setFontCss(treeId,treeNode){
    	return treeNode.status == 0 ? {"padding-top":"0","background-color":"silver","color":"#111","border":"1px #316AC5 dotted"} : {};
    }
    function createTable(treeNode){
    	var id=treeNode.id;
    	var name=treeNode.name;
    	var status=treeNode.status;
    	var access_order=treeNode.access_order;
    	var access_url=treeNode.access_url;
    	var target=treeNode.target;
    	var flagTure="";
    	var falgFalse="";
    	if(status==0){
    		falgFalse="checked=checked";
    	}else{
    		flagTure="checked=checked";
    	}
    	var targetTure="";
    	var targetFalse="";
    	if(target=='0'){
    		 targetFalse="checked=checked";
    	}else{
    		targetTure="checked=checked";
    	}
    	var html=" <table width='100%' cellspacing=10 cellpadding=10 id='table"+id+"'>"+
       "<tr><td style='width:50px'>权限编号</td><td>    <input type='text'     class='span4' name='id' value='"+id+"' readonly=readonly></td></tr>"+
       "<tr><td style='width:50px'>权限名称</td><td><input type='text'    style='height:17px' class='span4' name='name' value='"+name+"'></td></tr>"+
		"<tr><td>权限连接</td><td><input type='text'    style='height:17px'  class='span4'  name='access_url' value='"+access_url+"'></td></tr>"+
		"<tr><td>权限排序</td><td><input type='text'   style='height:17px'   class='span4'  name='access_order' value='"+access_order+"'></td></tr>"+
		"<tr> <td>菜单状态</td><td><input type='radio' name='status"+id+"' value=1 "+flagTure+">有效 &nbsp;<input type='radio' name='status"+id+"' "+falgFalse+" value=0>无效  </td></tr>"+
		"<tr> <td>权限显示</td><td><input type='radio' name='target"+id+"' value=1 "+targetTure+">外部 &nbsp;<input type='radio' name='target"+id+"' "+targetFalse+" value=0>内部  </td></tr>"+
		"</table>";
    	 return html;
    }
    function sub(){
    	act=[];
    	menu=[];
    	model=[];
    	var nodes = treeObj.getNodes();
    	 r(nodes);
    	  $.ajax({
              type: "post",
              dataType:"json",
              url: "/config/doAccess",
              data:{act:fisker_encode_v2(JSON.stringify(act)) ,menu:fisker_encode_v2(JSON.stringify(menu)),model:fisker_encode_v2(JSON.stringify(model))},
              //data:"&act="+encodeURIComponent(JSON.stringify(act))+"&menu="+encodeURIComponent(JSON.stringify(menu)) +"&model="+encodeURIComponent(JSON.stringify(model)),
              error:function (XMLHttpRequest, textStatus, errorThrown) {
                  alert("提交失败\n"+XMLHttpRequest.responseText+'\n');
              },
              success: function(msg){
                  if(msg.success==1){
                  	myAlert("保存成功!",3,'succeed',function(args){
                  		     //更新树节点
                  		     var r0=msg.arr[0],r1=msg.arr[1],r2=msg.arr[2];
                  		   	refreshTree(model,[],r0); 
                  		   	refreshTree(menu,r0,r1); 
                  		   	refreshTree(act,r1,r2); 
                  	}); 
                  }else if(msg.success==0){
                  	myAlert("保存失败!");
                  }
              }
         });
    }
    function fisker_encode_v2(s){
        var es = [],c='',ec='';
        s = s.split('');//10.19补 忘记ie不能下标访问字符串
        for(var i=0,length=s.length;i<length;i++){
            c = s[i];
            ec = encodeURIComponent(c);
            if(ec==c){
                ec = c.charCodeAt().toString(16);
                ec = ('00' + ec).slice(-2);
            }
            es.push(ec);
        }
        return es.join('').replace(/%/g,'').toUpperCase();
    }
    function  refreshTree(m,pidArr,nowArr){
        for(var i=0;i<m.length;i++){
	    	    var em=m[i];
	    	    var this_id=em.id;
	    	    var this_tId=em.tId;
	    	    var this_pId=em.pId;
	    	    var this_node= treeObj.getNodeByTId(this_tId);
	    	    if(em.isClick){
	    	    		this_node.name=em.access_name;
	    	    		this_node.isNew=false;
	    	    		this_node.access_order=em.access_order;
	    	    		this_node.access_url=em.access_url;
	    	    		this_node.status=em.status;
	    	    		this_node.target=em.target;
	    	    }
	    	    if(em.isNew){
	    	    	this_node.pId=pidArr[this_pId]==undefined?0:pidArr[this_pId];
	    	    	this_node.id=nowArr[this_id];
	    	    	this_node.isNew=false;
	    	    }
	    	    treeObj.updateNode(this_node);
	     }
    }
    function getMasterData(){   
    		var JsonStr = "&" + jQuery("#myform").serialize();
    	    return JsonStr;
    }
    function addNode(){
   	 		var nodes = treeObj.getSelectedNodes();
             if(nodes.length==0){
            		myAlert("请选择需要加载的节点!");
            	 return ;
             }
             treeNode=nodes[0];
             if(treeNode.level==3){
            	myAlert("最内层不允许新增节点!");
               	 return ; 
             }
             var nowNode= {
	            		 id:(100 + newCount)+"_new",
	            		 pId:treeNode.id,
	            		 status:1,
	            		 access_order:'',
	            		 access_url:'',
	            		 target:0,
	            		 isNew:true,
	            		 name:"new node" + (newCount++)
            		};
             treeObj.addNodes(treeNode,nowNode);
    }

   var status_str="";
    
    //递归获取所有节点
    function r(nodes){
    	if(nodes.length>0){
    		var l=nodes.length;
    		for(var i=0;i<l;i++){
    				var e=nodes[i];
    				var isNew=e.isNew;
    		    	var access_order="";
    		    	var access_url="";
    				var status="";
    		    	var target="";
    		    	var isClick=false;
    		    	var pId=e.pId;//父节点编号
    		    	var name=e.name;
    				if($('#table'+e.id).length>0){
    						isClick=true;
	    					access_order = $.trim($('#table'+e.id).find('input[name="access_order"]').val());
	    					access_url = $.trim($('#table'+e.id).find('input[name="access_url"]').val());
	    					status=$.trim($('#table'+e.id).find("input[name='status"+e.id+"']:checked").val());
	    					target=$.trim($('#table'+e.id).find("input[name='target"+e.id+"']:checked").val());
	    					name=$.trim($('#table'+e.id).find("input[name='name']").val());
    				}
					if(status=="0"&&e.id!=0){//如果当前节点无效
						status_str+="^"+e.id+"^";
				   }
				   if(status_str.indexOf("^"+pId+"^")>=0){//无效子节点
						status_str+="^"+e.id+"^";
						status="0";
						isClick=true;
					}	   
    				if(e.level==1){
	    				model.push({id:e.id,access_name:name,isNew:isNew,access_order:access_order,access_url:access_url,status:status,target:target,isClick:isClick,pId:0,depth:0,tId:e.tId}) ;
    				}
    				if(e.level==2){
    					menu.push({id:e.id,access_name:name,isNew:isNew,access_order:access_order,access_url:access_url,status:status,target:target,isClick:isClick,pId:pId,depth:1,tId:e.tId}) ;
    				}
    				if(e.level==3){
    					     act.push({id:e.id,access_name:name,isNew:isNew,access_order:access_order,access_url:access_url,status:status,target:target,isClick:isClick,pId:pId,depth:2,tId:e.tId}) ;
    				}
    				 if(e.children==undefined)continue;
    	    		 else  r(e.children);
    		}
    	}    
    }
</script>